//
//  NewFeatureCollectionViewController.swift
//  swift-GWYWeiBo
//
//  Created by x on 2017/4/6.
//  Copyright © 2017年 HLB. All rights reserved.
//
//写代码  自己的事情自己做
import UIKit

private let reuseIdentifier = "Cell"

class NewFeatureCollectionViewController: UICollectionViewController {
    
    /// 图片总数
    private let pageCount = 4;
    /// 布局对象
    private let flowLayout = XMGFlowLayout()
    
    init() {
        super.init(collectionViewLayout: flowLayout)
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Register cell classes
        collectionView?.register(NewFeatureCell.self, forCellWithReuseIdentifier: reuseIdentifier)

    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }
    
    // MARK: UICollectionViewDataSource
    
    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of items
        return pageCount
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! NewFeatureCell
        //print("indexPath===",indexPath.item)
        cell.pageIndex = indexPath.item
        return cell
    }
    
    /// 当一个cell显示完毕之后执行的方法
    ///
    /// - Parameters:
    ///   - collectionView: <#collectionView description#>
    ///   - cell: <#cell description#>
    ///   - indexPath: <#indexPath description#>
    override func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
        //这里得到大indexPath.item是上一个cell的索引  而不是当前cell的索引
        let path = collectionView.indexPathsForVisibleItems.last! //拿到显示完全cell的indexPath索引
        //print(path)
        if path.item == (pageCount-1) {
            //通过cell的索引拿到当前的cell
            let cell = collectionView.cellForItem(at: path) as! NewFeatureCell
            //cell执行按钮的动画
            cell.startAnimation()
        }
    }
}
//自己的事情自己做
//自定义cell
private class NewFeatureCell: UICollectionViewCell {
    
    var pageIndex: Int = 0 {
        didSet{
            iconView.image = UIImage.init(named: "new_feature_"+"\(pageIndex+1)")
        }
    }
    //执行按钮的动画
    func startAnimation() -> Void {
        iconBtu.isHidden = false
        //执行动画
        iconBtu.transform = CGAffineTransform(scaleX: 0.0, y: 0.0)
        iconBtu.isUserInteractionEnabled = false
        //ios8新增加的一个动画方法
        UIView.animate(withDuration: 3.0, delay: 0, usingSpringWithDamping: 1.0, initialSpringVelocity: 10, options: UIViewAnimationOptions.init(rawValue: 0), animations: {
            self.iconBtu.transform = CGAffineTransform.identity
        }, completion: { (_) in
            self.iconBtu.isUserInteractionEnabled = true
        })
    }
    func btuClick() -> Void {
        print(#function)
        //这里要跳转到主界面
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: GWYSwitchRootController), object: true)
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        //初始化
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() -> Void {
        
        //添加子控件
        iconView.frame = bounds
        iconView.contentMode = UIViewContentMode.scaleToFill//设置图片的模式 按比例缩放填充
        contentView.addSubview(iconView)
        
        contentView.addSubview(iconBtu)
    }
    //MARK: 懒加载 属性
    //私有属性是不能被访问的
    private lazy var iconView = UIImageView()
    
    /// 懒加载进入微博按钮
    private lazy var iconBtu = { () -> UIButton in
        let btu = UIButton()
        btu.setBackgroundImage(UIImage.init(named: "new_feature_button"), for: UIControlState.normal)
        btu.addTarget(self, action: #selector(btuClick), for: UIControlEvents.touchUpInside)
        btu.frame = CGRect(x:(self.bounds.size.width-(btu.currentBackgroundImage?.size.width)!)/2 , y: self.bounds.size.height - (btu.currentBackgroundImage?.size.height)!-160, width: (btu.currentBackgroundImage?.size.width)!, height: (btu.currentBackgroundImage?.size.height)!)
        btu.isHidden = true
        return btu
    }()
    
}
//自定义流水布局
private class XMGFlowLayout: UICollectionViewFlowLayout {
    
    /// 重写准备布局方法
    override func prepare() {
        //每个item的大小是collectionView的大小
        itemSize = UIScreen.main.bounds.size//(collectionView?.bounds.size)!
        minimumLineSpacing = 0;
        minimumInteritemSpacing = 0;
        scrollDirection = UICollectionViewScrollDirection.horizontal//设置滚动方向的水平
        collectionView?.bounces = false;
        collectionView?.showsHorizontalScrollIndicator = false;
        collectionView?.isPagingEnabled = true//设置整也滚动
    }
}










